package com.lcm.jnode.controller.admin;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.StringKit;
import com.lcm.jnode.interceptor.AdminInterceptor;
import com.lcm.jnode.model.Blog;
import com.lcm.jnode.model.DataTablesModel;
import com.lcm.jnode.model.User;

/**
 * 后台博文管理
 * @author L.cm
 * @date 2013-5-31 下午9:47:55
 */
@Before(AdminInterceptor.class)
public class AdminBlogController extends Controller {
	 /**
     * 后台 blog 列表页
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void index() {}
    
    /**
     * 后台 blog 列表
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
    public void list_json() {
        int iDisplayStart = getParaToInt("iDisplayStart", 0);
        int iDisplayLength = getParaToInt("iDisplayLength", 10);
        int pageNum =  iDisplayStart / iDisplayLength + 1;
        String sEcho = getPara("sEcho", "1");
    	String select = "SELECT b.id, b.title, b.blog_type, b.del_status, u.nick_name, b.update_time";
    	String sqlExceptSelect = "FROM blog AS b ,user_info AS u WHERE b.user_id = u.id ORDER BY b.id DESC";
    	DataTablesModel dataTable = Blog.dao.paginateDataTables(pageNum, 
    	        iDisplayLength, select, sqlExceptSelect, sEcho);
        renderJson(dataTable);
    }
    
    /**
     * 后台写博或跟新
     * @param     设定文件
     * @return void    返回类型
     * @throws
     */
	public void add_edit() {
		Integer id = getParaToInt();
		if(null != id){
			Blog blog = Blog.dao.findById(id);
			setAttr("blog", blog);
		}
	}

	/**
	 * 保存或更新博客
	 * @param     设定文件
	 * @return void    返回类型
	 * @throws
	 */
	public void save_update() {
		Blog blog = getModel(Blog.class);
		boolean state = false;
		if(null == blog.getInt(Blog.ID)){
			User user = getSessionAttr("user");
			blog.set(Blog.USER_ID, user.getInt(User.ID));
			state = Blog.dao.save(blog);
		} else {
			state = Blog.dao.update(blog);
		}
	    
		renderJson("state", state);
	}

	/**
	 * 删除或显示博文
	 * @param     设定文件
	 * @return void    返回类型
	 * @throws
	 */
	public void delete_show() {
		Blog blog = Blog.dao.findById(getParaToInt());
		boolean temp = false;
		if(StringKit.notNull(blog)){
			int status = blog.getInt(Blog.DEL_STATUS) == Blog.DEL_N ? Blog.DEL_Y : Blog.DEL_N;
			temp = blog.set(Blog.DEL_STATUS, status).update();
		} 
		renderJson("state", temp);
	}
}
